package com.rad.net.protocol.android.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


/** 
 * 类说明：输出输出工具类，负责处理输入输出流和字符串或者byte数组之间的转换
 * @author  xinhui.cheng
 * @date    2014-9-4
 * @version 1.0
 */
public class IOUtils {

	private IOUtils(){}
	
	/**
	 * 将输入流对象转为字符串
	 * @param inputStream 输入流对象
	 * @return 结果字符串或者null
	 */
	public static String inputStream2String(InputStream inputStream) {
		if(inputStream == null){
			return null;
		}
		String str = "";
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] data = new byte[1024];
		try {
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
			str = new String(outputStream.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 将输出流对象转换为byte数组
	 * @param inputStream 输入流对象
	 * @return byte数组或者null
	 */
	public static byte[] inputStream2ByteArray(InputStream inputStream) {
		if(inputStream == null){
			return null;
		}
		byte[] result = null;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] data = new byte[1024];
		try {
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
			result = outputStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 将输入流对象转换为byte数组输入流
	 * @param inputStream 输入流对象
	 * @return byte数组输入流对象或者null
	 */
	public static ByteArrayInputStream inputStream2ByteArrayIS(InputStream inputStream) {
		if(inputStream == null){
			return null;
		}
		return new ByteArrayInputStream(inputStream2ByteArray(inputStream));
	}
	
}
